package multiplayerShooter;

import java.util.ArrayList;
import java.util.ListIterator;

public class MovingBlock extends Block implements Runnable {
	int xMin;
	int xMax;
	int yMin;
	int yMax;
	int xChange = 0;
	int yChange = 0;
	ArrayList<Player> playersOnBlock = new ArrayList<Player>();
	ListIterator<Player> it;

	public MovingBlock(int xMin_, int xMax_, int yMin_, int yMax_) {

		this.xMin = xMin_;
		this.x = this.xMin;
		this.xMax = xMax_;
		this.yMin = yMin_;
		this.y = yMin_;
		this.yMax = yMax_;
		if (this.xMin != this.xMax)
			this.xChange = 1;
		if (this.yMin != this.yMax)
			this.yChange = 1;

		Thread th = new Thread(this);
		th.start();
	}

	public boolean onBlock(int px, int py, Player player) {
		if (super.onBlock(px, py, player)) {
			if (!this.playersOnBlock.contains(player)) {
				if (this.it != null)
					this.it.add(player);
				else
					this.playersOnBlock.add(player);

			}
			return true;
		}

		return false;
	}

	public void run() {
		while (true) {

			
			if (this.xMin == this.xMax)
				;
			else if (this.x <= this.xMin) {
				this.xChange = 1;
			} else if (this.x >= this.xMax) {
				this.xChange = -1;
			}
			if (this.xMin != this.xMax) {
				this.it = this.playersOnBlock.listIterator();
				while (this.it.hasNext()) {

					Player p = (Player) this.it.next();

					if (super.onBlock(p.getXPos() + 37, p.yPos + 84, p)) {
						p.setXPos(p.getXPos() + this.xChange);
					} else {
						this.it.remove();
					}
				}
				this.x += this.xChange;
			}

			if (this.yMin == this.yMax)
				;
			else if (this.y <= this.yMin) {
				this.yChange = 1;
			} else if (this.y >= this.yMax) {
				this.yChange = -1;
			}
			if (this.yMin != this.yMax) {
				this.it = this.playersOnBlock.listIterator();
				while (this.it.hasNext()) {

					Player p = (Player) this.it.next();

					if (super.onBlock(p.getXPos() + 37, p.yPos + 84, p)) {
						p.yPos += this.yChange;
					} else
					{
						this.it.remove();
					}
				}
				this.y += this.yChange;
			}
			
			try {
				Thread.sleep(10);
			} catch (Exception e) {
			}
		}
	}
}